﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;
using System.Collections.Generic;

namespace MII_FIF.Layouts.MII_FIF.Checklist
{
    public partial class FormCHPhysicalServer : LayoutsPageBase
    {
        SqlConnection conn;
        DataTable dt;
        SqlDataAdapter adapt;
        //string connStr = "Data Source=sp2013-server;Initial Catalog=InventoryManagement;User ID=sa;Password=P@ssw0rd";
        string queryStr = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Generic.IsUserInGroup(Configuration.ChecklistGroupName))
            {
                if (!IsPostBack)
                {
                    btnDownload.Visible = false;
                    lblFileName.Text = "No File";

                    if (Request.QueryString["ID"] != null)
                    {
                        ViewState["ID"] = Request.QueryString["ID"].ToString();
                        LoadDataView(ViewState["ID"].ToString());
                    }
                    else
                    {
                        LoadDatacabang();
                        btnRemove.Visible = false;
                        LinkAttachment.Visible = false;
                        lblType.Text = "Select";
                    }
                    ((Label)Header.FindControl("lblHeader")).Text = "Form Checklist Physical Server";
                }
            }
            else
            {
                Response.Redirect(Generic.GenLink("/"));
            }
        }

        protected DataTable ExecuteDataTable(string queryStr)
        {
            //conn = new SqlConnection(connStr);
            conn = new SqlConnection(Configuration.DBConnection());
            conn.Open();
            adapt = new SqlDataAdapter(queryStr, conn);
            dt = new DataTable();
            adapt.Fill(dt);
            conn.Dispose();
            return dt;
        }

        //Load data

        void LoadDataView(String ID)
        {
            try
            {
                queryStr = @"EXEC SP_SelectDataViewCHPSperID '" + ID + "'";

                dt = ExecuteDataTable(queryStr);
                int i = 0;
                txtInventoryBy.Text = dt.Rows[i]["InventoryBy"].ToString();
                string[] tanggal = dt.Rows[i]["InventoryDate"].ToString().Split(' ');
                txtInventoryDate.Text = tanggal[0];
                txtStartFrom.Text = dt.Rows[i]["StartFrom"].ToString();
                txtSystemDetail.Text = dt.Rows[i]["SystemDetail"].ToString();
                txtIPManagement.Text = dt.Rows[i]["IPManagement"].ToString();
                txtIPHost.Text = dt.Rows[i]["IPHost"].ToString();
                txtPathNumber.Text = dt.Rows[i]["PathNumber"].ToString();
                txtSerialNumber.Text = dt.Rows[i]["SerialNumber"].ToString();
                txtProcessorUnit.Text = dt.Rows[i]["Processor"].ToString();
                txtProcessorCore.Text = dt.Rows[i]["Core"].ToString();

                txtRAMGB.Text = dt.Rows[i]["RAM"].ToString();
                txtRAMPcs.Text = dt.Rows[i]["JumlahRAM"].ToString();
                txtRAMTotal.Text = (Double.Parse(txtRAMGB.Text) * Double.Parse(txtRAMPcs.Text)).ToString();

                txtHarddiskUnit.Text = dt.Rows[i]["HDD"].ToString();
                txtHarddiskGB.Text = dt.Rows[i]["KapasitasHDD"].ToString();
                txtApplication.Text = dt.Rows[i]["Application"].ToString();

                ViewState["Link"] = dt.Rows[i]["URLAttachment"].ToString();
                if (ViewState["Link"] == "")
                    btnDownload.Visible = false;
                else
                {
                    lblFileName.Visible = false;
                    btnDownload.Visible = true;
                }

                lblType.Text = "Inventory";

                ddlRaidDetail.Items.Add(new ListItem(dt.Rows[i]["RaidDetail"].ToString(), dt.Rows[i]["RaidDetail"].ToString()));

                rblSystemClass.SelectedValue = dt.Rows[i]["SystemClass"].ToString();

                ddlLocation.Enabled = false;
                ddlLocation.Items.Add(new ListItem(dt.Rows[i]["Cabang"].ToString(), dt.Rows[i]["DataCabang"].ToString()));

                ddlRackNumber.Enabled = false;
                ddlRackNumber.Items.Add(new ListItem(dt.Rows[i]["RackNumber"].ToString(), dt.Rows[i]["ID_RackNumber"].ToString()));

                ddlLabelname.Enabled = false;
                ddlLabelname.Items.Add(new ListItem(dt.Rows[i]["LabelName"].ToString(), dt.Rows[i]["LabelName"].ToString()));

                ddlSystemBrand.Items.Add(new ListItem(dt.Rows[i]["SBTitle"].ToString(), dt.Rows[i]["SBTitle"].ToString()));
                ddlSystemType.Items.Add(new ListItem(dt.Rows[i]["STTitle"].ToString(), dt.Rows[i]["STTitle"].ToString()));
                ddlOperatingSystem.Items.Add(new ListItem(dt.Rows[i]["OSTitle"].ToString(), dt.Rows[i]["OSTitle"].ToString()));

                rblPhysical.Enabled = false;
                rblPhysical.SelectedValue = dt.Rows[i]["CHPhysical"].ToString();
                rblPowerSupply.Enabled = false;
                rblPowerSupply.SelectedValue = dt.Rows[i]["CHPower"].ToString();
                rblHarddisk.Enabled = false;
                rblHarddisk.SelectedValue = dt.Rows[i]["CHHDD"].ToString();
                rblMemory.Enabled = false;
                rblMemory.SelectedValue = dt.Rows[i]["CHMemory"].ToString();
                rblFAN.Enabled = false;
                rblFAN.SelectedValue = dt.Rows[i]["CHFan"].ToString();
                rblEthernet.Enabled = false;
                rblEthernet.SelectedValue = dt.Rows[i]["CHEthernet"].ToString();

                txtNotes.Enabled = false;
                txtNotes.Text = dt.Rows[i]["CHNote"].ToString();

                String CHattachment = dt.Rows[i]["CHAttachment"].ToString();

                if (CHattachment != "")
                {
                    LinkAttachment.Text = dt.Rows[i]["CHAttachment"].ToString();
                    LinkAttachment.NavigateUrl = dt.Rows[i]["CHAttachment"].ToString();
                }
                else
                    LinkAttachment.Text = "No File";

                btnRemove.Visible = true;
                btnSubmit.Visible = false;
                FUAttachment.Visible = false;
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        void LoadDatacabang()
        {
            try
            {
                queryStr = @"EXEC SP_SelectDataLocation";

                dt = ExecuteDataTable(queryStr);
                //bool isExists = false;
                ddlLocation.Items.Clear();
                ddlLocation.Items.Add("- SELECT -");

                if (dt.Rows.Count > 0)
                {
                    int i = 0;

                    for (i = 0; i < dt.Rows.Count; i++)
                    {
                        ddlLocation.Items.Add(new ListItem(dt.Rows[i]["Location"].ToString(), dt.Rows[i]["ID"].ToString()));
                    }
                }

            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        void LoadDataRack(String Location)
        {
            try
            {
                if (Location == "- SELECT -")
                    clearform();
                else
                {
                    queryStr = @"EXEC SP_SelectDataRackPSperlocation '" + Location + "'";

                    dt = ExecuteDataTable(queryStr);
                    //bool isExists = false;
                    ddlRackNumber.Items.Clear();
                    ddlRackNumber.Items.Add("- SELECT -");

                    if (dt.Rows.Count > 0)
                    {
                        int i = 0;

                        for (i = 0; i < dt.Rows.Count; i++)
                        {
                            ddlRackNumber.Items.Add(new ListItem(dt.Rows[i]["RackNumber"].ToString(), dt.Rows[i]["ID"].ToString()));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        void LoadDataLabel(String Cabang, String Rack)
        {
            try
            {
                if (Rack == "- SELECT -")
                    clearform();
                else
                {
                    queryStr = @"EXEC SP_SelectDataLabelPSperlocationrack '" + Cabang + "','" + Rack + "'";

                    dt = ExecuteDataTable(queryStr);
                    //bool isExists = false;
                    ddlLabelname.Items.Clear();
                    ddlLabelname.Items.Add("- SELECT -");

                    if (dt.Rows.Count > 0)
                    {
                        int i = 0;

                        for (i = 0; i < dt.Rows.Count; i++)
                        {
                            ddlLabelname.Items.Add(new ListItem(dt.Rows[i]["LabelName"].ToString(), dt.Rows[i]["LabelName"].ToString()));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        void LoadDataSystemBrand(String Cabang, String Rack, String Label)
        {
            queryStr = @"EXEC SP_SelectDataSysbrandperlabel '" + Cabang + "','" + Rack + "','" + Label + "'";
            dt = ExecuteDataTable(queryStr);
            int i = 0;
            ddlSystemBrand.Items.Clear();
            ddlSystemBrand.Items.Add(new ListItem(dt.Rows[i]["Title"].ToString(), dt.Rows[i]["ID"].ToString()));
        }
        void LoadDataSystemType(String Cabang, String Rack, String Label)
        {
            queryStr = @"EXEC SP_SelectDataSysTypeperlabel '" + Cabang + "','" + Rack + "','" + Label + "'";
            dt = ExecuteDataTable(queryStr);
            int i = 0;
            ddlSystemType.Items.Clear();
            ddlSystemType.Items.Add(new ListItem(dt.Rows[i]["Title"].ToString(), dt.Rows[i]["ID"].ToString()));
        }
        void LoadDataOS(String Cabang, String Rack, String Label)
        {
            queryStr = @"EXEC SP_SelectDataOSperlabel '" + Cabang + "','" + Rack + "','" + Label + "'";
            dt = ExecuteDataTable(queryStr);
            int i = 0;
            ddlOperatingSystem.Items.Clear();
            ddlOperatingSystem.Items.Add(new ListItem(dt.Rows[i]["Title"].ToString(), dt.Rows[i]["ID"].ToString()));
        }

        void LoadDataAll(String Cabang, String Rack, String Label)
        {
            if (Label == "- SELECT -")
                clearform();
            else
            {
                try
                {
                    queryStr = @"EXEC SP_SelectDataAllPSperlabel '" + Cabang + "','" + Rack + "','" + Label + "'";
                    dt = ExecuteDataTable(queryStr);
                    int i = 0;
                    lblIDPS.Text = dt.Rows[i]["ID"].ToString();
                    txtInventoryBy.Text = dt.Rows[i]["InventoryBy"].ToString();
                    string[] tanggal = dt.Rows[i]["InventoryDate"].ToString().Split(' ');
                    txtInventoryDate.Text = tanggal[0];
                    txtStartFrom.Text = dt.Rows[i]["StartFrom"].ToString();
                    txtSystemDetail.Text = dt.Rows[i]["SystemDetail"].ToString();
                    txtIPManagement.Text = dt.Rows[i]["IPManagement"].ToString();
                    txtIPHost.Text = dt.Rows[i]["IPHost"].ToString();
                    txtPathNumber.Text = dt.Rows[i]["PathNumber"].ToString();
                    txtSerialNumber.Text = dt.Rows[i]["SerialNumber"].ToString();
                    txtProcessorUnit.Text = dt.Rows[i]["Processor"].ToString();
                    txtProcessorCore.Text = dt.Rows[i]["Core"].ToString();

                    txtRAMGB.Text = dt.Rows[i]["RAM"].ToString();
                    txtRAMPcs.Text = dt.Rows[i]["JumlahRAM"].ToString();
                    txtRAMTotal.Text = (Double.Parse(txtRAMGB.Text) * Double.Parse(txtRAMPcs.Text)).ToString();

                    txtHarddiskUnit.Text = dt.Rows[i]["HDD"].ToString();
                    txtHarddiskGB.Text = dt.Rows[i]["KapasitasHDD"].ToString();
                    txtApplication.Text = dt.Rows[i]["Application"].ToString();

                    ViewState["Link"] = dt.Rows[i]["URLAttachment"].ToString();
                    if (ViewState["Link"] == "")
                        btnDownload.Visible = false;
                    else
                    {
                        lblFileName.Visible = false;
                        btnDownload.Visible = true;
                    }

                    ddlRaidDetail.Items.Add(new ListItem(dt.Rows[i]["RaidDetail"].ToString(), dt.Rows[i]["RaidDetail"].ToString()));

                    rblSystemClass.SelectedValue = dt.Rows[i]["SystemClass"].ToString();


                    LoadDataSystemBrand(Cabang, Rack, Label);
                    LoadDataSystemType(Cabang, Rack, Label);
                    LoadDataOS(Cabang, Rack, Label);
                }
                catch (Exception ex)
                {
                    lblError.Text = ex.Message;
                }
            }
        }

        void clearform()
        {
            txtInventoryBy.Text = string.Empty;
            txtStartFrom.Text = string.Empty;
            txtSystemDetail.Text = string.Empty;
            txtIPManagement.Text = string.Empty;
            txtIPHost.Text = string.Empty;
            txtPathNumber.Text = string.Empty;
            txtSerialNumber.Text = string.Empty;
            txtProcessorUnit.Text = string.Empty;
            txtProcessorCore.Text = string.Empty;

            txtRAMGB.Text = string.Empty;
            txtRAMPcs.Text = string.Empty;
            txtRAMTotal.Text = string.Empty;

            txtHarddiskUnit.Text = string.Empty;
            txtHarddiskGB.Text = string.Empty;
            txtApplication.Text = string.Empty;

            ddlSystemBrand.Items.Clear();
            ddlSystemType.Items.Clear();
            ddlOperatingSystem.Items.Clear();
            ddlRaidDetail.Items.Clear();
            rblSystemClass.ClearSelection();
        }

        void RedirectPageView(String status)
        {
            Response.Redirect(Generic.GenLink("/_Layouts/MII_FIF/Checklist/ViewCHPhysicalServer.aspx?Status="+status+""));
        }

        protected void ddlLocation_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDataRack(ddlLocation.SelectedValue.ToString());

            //Reset ddlName
            ddlLabelname.Items.Clear();

            //Reset Form
            clearform();
        }

        protected void ddlRackNumber_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDataLabel(ddlLocation.SelectedValue.ToString(), ddlRackNumber.SelectedValue.ToString());
            
            //Reset Form
            clearform();
        }

        protected void ddlLabelname_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDataAll(ddlLocation.SelectedValue.ToString(), ddlRackNumber.SelectedValue.ToString(),ddlLabelname.SelectedValue.ToString());
        }

        public byte[] GetFileBytes()
        {
            Stream stream = FUAttachment.PostedFile.InputStream;
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, (int)stream.Length);
            stream.Close();
            return bytes;
        }

        public void UploadFile(string siteUrl, string docLibraryName, string folderPath,
            string fileName, byte[] fileByteArray, Dictionary<string, string> columnValues, bool overWrite)
        {
            try
            {
                string fileUrl = siteUrl + docLibraryName + folderPath + fileName;
                string currentFolder = siteUrl + docLibraryName;
                using (SPWeb web = new SPSite(siteUrl).OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPFolder folder = web.Folders[docLibraryName];
                    if (folderPath != string.Empty)
                    {
                        foreach (string subFolder in folderPath.Split('/'))
                        {
                            currentFolder = currentFolder + subFolder;
                            if (!web.GetFolder(currentFolder).Exists)
                            {
                                folder.SubFolders.Add(subFolder);
                            }
                            folder = folder.SubFolders[subFolder];
                        }
                    }
                    if (overWrite || !web.GetFile(fileUrl).Exists)
                    {
                        folder.Files.Add(fileName, fileByteArray, true);
                    }
                    else
                    {
                        folder.Files[fileName].CheckOut();
                        folder.Files.Add(fileName, fileByteArray, true);
                        folder.Files[fileName].CheckIn(String.Empty);
                    }
                    SPFile file = folder.Files[fileUrl];
                    foreach (KeyValuePair<string, string> columnValue in columnValues)
                    {
                        file.Item.Properties[columnValue.Key] = columnValue.Value;
                    }
                    file.Item.Update();
                }
            }
            catch (Exception ex)
            {
                //TODO: Add Exception Handling 
                lblError.Text = ex.Message.ToString();
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                String IDPS = lblIDPS.Text.ToString();
                String CHPS = rblPhysical.SelectedValue.ToString();
                String CHMemory = rblMemory.SelectedValue.ToString();
                String CHPower = rblPowerSupply.SelectedValue.ToString();
                String CHFan = rblFAN.SelectedValue.ToString();
                String CHHDD = rblHarddisk.SelectedValue.ToString();
                String CHNet = rblEthernet.SelectedValue.ToString();
                String CHNote = txtNotes.Text.ToString();
                String CHBy = SPContext.Current.Web.CurrentUser.Name;

                string fileName = Path.GetFileName(FUAttachment.PostedFile.FileName);

                String AttachmentURL = "";

                if (IDPS != "" && CHPS != "" && CHMemory != "" && CHPower != "" && CHFan != "" && CHHDD != "" && CHNet != "" && CHNote != "")
                {
                    //if (FUAttachment.PostedFile != null)
                    //{
                    //    string siteUrl = @"http://sp2013-server/";
                    //    string docLibraryName = "Shared Documents";
                    //    //string docLibraryURL = "Shared%20Documents";
                    //    string folderPath = "";
                    //    string fileName = Path.GetFileName(FUAttachment.PostedFile.FileName);
                    //    byte[] fileBytes = GetFileBytes();
                    //    Dictionary<string, string> columnValues = new Dictionary<string, string>();
                    //    columnValues.Add("Document Type", "Physical Server");
                    //    columnValues.Add("Author", CHBy);
                    //    UploadFile(siteUrl, docLibraryName, folderPath, fileName, fileBytes, columnValues, true);

                    if (fileName != "")
                        AttachmentURL = Generic.UploadFile(FUAttachment);
                    //}

                    queryStr = @"EXEC SP_InsertDataCHPS '" + IDPS + "','" + CHPS + "','" + CHPower +
                                "','" + CHHDD + "','" + CHMemory + "','" + CHFan + "','" + CHNet + "','" + CHNote + "','" + CHBy + "','" + AttachmentURL + "'";

                    ExecuteDataTable(queryStr);

                    RedirectPageView("Submitted");
                    //Response.Redirect(Generic.GenLink("/_Layouts/MII_FIF/Checklist/ViewCHPhysicalServer.aspx"));
                }
                else
                    lblError.Text = "Pilih Physical Server & Isi Seluruh Form Checklistnya (Attachment Optional)";
                
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message.ToString();
            }
           
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            RedirectPageView("");
            //Response.Redirect(Generic.GenLink("/_Layouts/MII_FIF/Checklist/ViewCHPhysicalServer.aspx"));
        }

        protected void btnRemove_Click(object sender, EventArgs e)
        {
            try
            {
                queryStr = @"EXEC SP_DeleteDataCHPS '" + ViewState["ID"].ToString() + "'";

                ExecuteDataTable(queryStr);

                RedirectPageView("Removed");
                //Response.Redirect(Generic.GenLink("/_Layouts/MII_FIF/Checklist/ViewCHPhysicalServer.aspx"));
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message.ToString();
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            try
            {
                string script =
                               "function download() {" +
                               "var link ='" + ViewState["Link"] + "';" +
                               "var retvalue = window.open('" + Generic.GenLink("/_layouts/MII_FIF/Download.aspx") + "?links=' + link"
                             + ", '', 'width=1000,height=1000');}";

                Page.ClientScript.RegisterClientScriptBlock(typeof(System.Web.UI.Page), "opendownload", script, true);
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message.ToString();
            }
        }
    }
}
